<template>
  <el-dialog v-model="show"
             title="编辑角色"
             width="500"
             :draggable="true"
             :close-on-click-modal="false">
    <el-form ref="formRef" :rules="rules" :model="form" label-width="90px" class="p-r-20">
      <el-form-item label="角色名" prop="name">
        <el-input v-model="form.name" />
      </el-form-item>
      <el-form-item label="备注">
        <el-input v-model="form.remark" type="textarea" />
      </el-form-item>
      <el-form-item label="禁用">
        <el-switch v-model="form.disabled" :active-value="1" :inactive-value="0" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="hideComp" style="padding: 0 20px" v-if="!loading">
        <span class="iconfont iaiai-close f20 m-r-5"></span>
        取消
      </el-button>
      <el-button type="primary" style="padding: 0 20px" :loading="loading" @click="edit" plain>
        <span class="iconfont iaiai-correct f20 m-r-5" v-if="!loading"></span>
        保存
      </el-button>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import {ref, defineExpose, defineEmits, inject} from "vue"
import {FormInstance, FormRules} from "element-plus"

const $api = inject('$api')
const $post = inject('$post')
const $toast = inject('$toast')
const emit = defineEmits(['onsuccess'])
const show = ref(false)
const loading = ref(false)

interface RuleForm {
  id: string
  name: string
  remark: string
  disabled: number
}
const formRef = ref<FormInstance>()
const form = ref<RuleForm>({
  id:"",
  name: "",
  remark: "",
  disabled: 0,
})

const rules = ref<FormRules<RuleForm>>({
  name: [
    { required: true, message: '请设置角色名', trigger: 'blur' },
  ],
})

function edit(){
  formRef.value.validate((valid, fields) => {
    if (valid) {
      loading.value = true

      $post($api.roleEdit,form.value).then((res:any)=>{
        loading.value = false
        show.value = false
        emit('onsuccess')
        $toast.success('保存成功')
      }).catch((err:any)=>{
        loading.value = false
      })
    }
  })
}

function showComp(id:any){
  form.value.id = id
  form.value.name = ""
  form.value.remark = ""
  form.value.disabled = 0

  show.value = true

  $post($api.roleDetail,{id:form.value.id}).then((res:any)=>{
    form.value.name = res.data["result"].name
    form.value.remark = res.data["result"].remark
    form.value.disabled = res.data["result"].disabled
  })
}
function hideComp(){
  show.value = false
}

defineExpose({
  showComp,
})
</script>

<style lang="scss" scoped>

</style>
